/**
 * PLM项目模块统一导入配置文件
 * 使用静态导入路径，避免动态require
 */

const pathResolver = require('./path_resolver.js');

// 定义默认npm配置
const defaultNpmConfig = {
  // MobX相关
  mobx: {
    observable: (obj) => obj,
    action: (fn) => fn,
    computed: (fn) => fn,
    configure: () => {},
    autorun: (fn) => { fn(); return () => {}; }
  },
  createStoreBindings: (context, options) => {
    console.warn('[PLM path_import] 使用兼容版createStoreBindings');
    return {
      updateStoreBindings: () => {},
      destroyStoreBindings: () => {}
    };
  },
  dayjs: function(date) {
    const d = date ? new Date(date) : new Date();
    return {
      format: (fmt) => {
        return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
      }
    };
  }
};

// 导入npm配置模块
let npmConfig;
try {
  // 使用静态路径导入
  npmConfig = require('../../../config/npm_config.js');
  console.log('[path_import.js] 成功导入npm_config');
} catch (e) {
  console.error('[PLM] 加载全局npm配置失败，使用本地兼容实现:', e.message);
  npmConfig = defaultNpmConfig;
}

// 直接导入辅助模块 - 页面上下文
let pageHelperPage, cloudHelperPage, timeHelperPage, validateHelperPage, 
    fileHelperPage, routerHelperPage, dataHelperPage, cacheHelperPage;

try {
  pageHelperPage = require('../helpers/page_helper.js');
} catch (e) {
  try {
    pageHelperPage = require('../../../helpers/page_helper.js');
  } catch (e) {
    console.error('[path_import.js] 导入page_helper失败:', e.message);
    pageHelperPage = { showModal: (msg) => wx.showToast({ title: msg, icon: 'none' }) };
  }
}

try {
  cloudHelperPage = require('../helpers/cloud_helper.js');
} catch (e) {
  try {
    cloudHelperPage = require('../../../helpers/cloud_helper.js');
  } catch (e) {
    console.error('[path_import.js] 导入cloud_helper失败:', e.message);
    cloudHelperPage = { callFunction: () => Promise.reject('云函数未实现') };
  }
}

try {
  timeHelperPage = require('../helpers/time_helper.js');
} catch (e) {
  try {
    timeHelperPage = require('../../../helpers/time_helper.js');
  } catch (e) {
    console.error('[path_import.js] 导入time_helper失败:', e.message);
    timeHelperPage = { fmtDateCHN: () => '未知日期' };
  }
}

try {
  // 使用静态字符串路径
  validateHelperPage = require('../helpers/validate_helper.js');
} catch (e) {
  console.error('[path_import.js] 导入validate_helper失败:', e.message);
  validateHelperPage = { checkRequired: (val) => val ? '' : '不能为空' };
}

try {
  // 使用静态字符串路径
  fileHelperPage = require('../helpers/file_helper.js');
} catch (e) {
  console.error('[path_import.js] 导入file_helper失败:', e.message);
  fileHelperPage = { openDoc: () => wx.showToast({ title: '文件功能未实现', icon: 'none' }) };
}

try {
  // 使用静态字符串路径
  routerHelperPage = require('../helpers/router_helper.js');
} catch (e) {
  console.error('[path_import.js] 导入router_helper失败:', e.message);
  routerHelperPage = { navigateTo: (url) => wx.navigateTo({ url }) };
}

try {
  // 使用静态字符串路径
  dataHelperPage = require('../helpers/data_helper.js');
} catch (e) {
  console.error('[path_import.js] 导入data_helper失败:', e.message);
  dataHelperPage = { deepClone: (obj) => JSON.parse(JSON.stringify(obj)) };
}

try {
  cacheHelperPage = require('../helpers/cache_helper.js');
} catch (e) {
  try {
    cacheHelperPage = require('../../../helpers/cache_helper.js');
  } catch (e) {
    console.error('[path_import.js] 导入cache_helper失败:', e.message);
    cacheHelperPage = { 
      set: (k, v) => wx.setStorageSync(k, v),
      get: (k) => wx.getStorageSync(k),
      remove: (k) => wx.removeStorageSync(k) 
    };
  }
}

// 导入全局模块配置
let moduleConfig;
try {
  moduleConfig = require('./module_config.js');
} catch (e) {
  console.error('[path_import.js] 导入module_config失败:', e.message);
  moduleConfig = {};
}

// 导入文件相关模块
let FileBiz;
let fileUtil;

try {
  FileBiz = require('../comm/biz/file_biz.js');
  console.log('[path_import.js] 成功导入FileBiz (../comm/biz/file_biz.js)');
} catch (e1) {
  try {
    FileBiz = require('../../comm/biz/file_biz.js');
    console.log('[path_import.js] 成功导入FileBiz (../../comm/biz/file_biz.js)');
  } catch (e2) {
    console.error('[path_import.js] 导入FileBiz失败:', e2.message);
    // 提供默认实现
    FileBiz = {
      openFile: async () => {
        wx.showToast({ title: '文件功能未实现', icon: 'none' });
        return Promise.resolve();
      },
      downloadFile: async () => {
        wx.showToast({ title: '文件功能未实现', icon: 'none' });
        return Promise.resolve();
      }
    };
  }
}

try {
  // 使用静态字符串路径
  fileUtil = require('../../../helpers/file_util.js');
  console.log('[path_import.js] 成功导入fileUtil (../../../helpers/file_util.js)');
} catch (e1) {
  try {
    fileUtil = require('../helpers/file_util.js');
    console.log('[path_import.js] 成功导入fileUtil (../helpers/file_util.js)');
  } catch (e2) {
    console.error('[path_import.js] 导入fileUtil失败:', e2.message);
    // 提供默认实现
    fileUtil = {
      getFileIcon: (filename) => {
        const ext = (filename || '').split('.').pop().toLowerCase();
        if (['jpg', 'jpeg', 'png', 'gif'].includes(ext)) return '/images/file/image.png';
        if (['doc', 'docx'].includes(ext)) return '/images/file/word.png';
        if (['xls', 'xlsx'].includes(ext)) return '/images/file/excel.png';
        if (['ppt', 'pptx'].includes(ext)) return '/images/file/ppt.png';
        if (['pdf'].includes(ext)) return '/images/file/pdf.png';
        return '/images/file/unknown.png';
      },
      getExtByMime: () => 'unknown'
    };
  }
}

/**
 * 获取全局辅助模块
 * @returns {object} 全局辅助模块配置
 */
function getGlobalHelpers() {
  try {
    return {
      pageHelper: pageHelperPage,
      cloudHelper: cloudHelperPage,
      timeHelper: timeHelperPage,
      validate: validateHelperPage,
      fileHelper: fileHelperPage,
      routerHelper: routerHelperPage,
      dataHelper: dataHelperPage,
      cacheHelper: cacheHelperPage,
      
      // 从npmConfig直接导入MobX相关模块
      mobx: npmConfig.mobx,
      createStoreBindings: npmConfig.createStoreBindings,
      storeBindingsBehavior: npmConfig.storeBindingsBehavior,
      dayjs: npmConfig.dayjs
    };
  } catch (err) {
    console.error('[path_import.js] 加载全局模块配置失败', err);
    
    // 提供备用方案 - 直接使用已导入的静态模块
    return {
      pageHelper: pageHelperPage,
      cloudHelper: cloudHelperPage,
      timeHelper: timeHelperPage,
      validate: {
        // 备用验证功能
        checkRequired: (val, desc = '') => val ? '' : `${desc}不能为空`
      },
      routerHelper: {
        navigateTo: (url) => wx.navigateTo({ url })
      },
      // 基本的mobx实现
      mobx: defaultNpmConfig.mobx,
      createStoreBindings: defaultNpmConfig.createStoreBindings,
      dayjs: defaultNpmConfig.dayjs
    };
  }
}

module.exports = {
  getGlobalHelpers,
  pathResolver,
  // 直接导出关键npm模块，方便导入
  createStoreBindings: npmConfig.createStoreBindings,
  mobx: npmConfig.mobx,
  dayjs: npmConfig.dayjs,
  // 导出文件相关模块
  FileBiz,
  fileUtil
}; 